package cn.tedu.kcircle.gateway.filter;

import cn.tedu.kcircle.common.consts.HttpConst;
import cn.tedu.kcircle.passport.api.rpc.PassportRpcApi;
import cn.tedu.kcircle.passport.protocol.dto.UserInfoDTO;
import cn.tedu.kcircle.passport.protocol.dto.UserLoginDTO;
import lombok.AllArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@AllArgsConstructor
public class JwtAuthorizationFilter implements GlobalFilter, Ordered, HttpConst {
    private PassportRpcApi passportRpcApi;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        HttpHeaders headers = request.getHeaders();
        String jwt = headers.getFirst(HEADER_AUTHORIZATION);
        if(jwt!=null){
            String userAgent = headers.getFirst(HEADER_USER_AGENT);
            String userAddr = request.getRemoteAddress().getHostName();
            UserLoginDTO userLoginDTO = new UserLoginDTO().setJwt(jwt).setUserAgent(userAgent).setUserAddr(userAddr);
            UserInfoDTO userInfoDTO = passportRpcApi.checkLogin(userLoginDTO);
            ServerHttpRequest eRequest = request.mutate().headers(httpHeaders -> httpHeaders.add(HEADER_USER_ID, String.valueOf(userInfoDTO.getUserId()))).build();
            return chain.filter(exchange.mutate().request(eRequest).build());
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 100;
    }
}
